#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "FIFO.h"

#define true 1
#define false 0

FIFO *InitFIFO(const char *name)
{
    FIFO *f=(FIFO*)malloc(sizeof(FIFO));
    if(f==NULL)
    {
        printf("initFIFO malloc error\n");
        return NULL;
    }
    int ret=mkfifo(name,S_IRUSR|S_IWUSR);
    if(ret==1)
    {
        printf("the FIFO is exit\n");
    }
    strcpy(f->Name,name);
    return f;
}

int OpenFIFO(FIFO *f,OpenMode mode)
{
    if(mode==ReadOnly)
    {
        f->fd=open(f->Name,O_RDONLY);
        if(f->fd==-1)
        {
            perror("OpenFIFO");
            return false;
        }
    }
    if(mode==WriteOnly)
    {
        f->fd=open(f->Name,O_WRONLY);
        if(f->fd==-1)
        {
            perror("OpenFIFO");
            return false;
        }
    }
    f->mode=mode;
    return true;
}

int ReadFromFIFO(FIFO *f, void *ptr, unsigned long size)
{
    if(f->mode==WriteOnly)
    {
        printf("FIFO mode is writeonly,cannot read\n");
        return false;
    }
    if(read(f->fd,ptr,size)<=0)
    {
        perror("ReadFromFIFO");
        return false;
    }
    return true;
}

int WriteToFIFO(FIFO *f, void *ptr, unsigned long size)
{
    if(f->mode==ReadOnly)
    {
        printf("FIFO mode is readonly,cannot write\n");
        return false;
    }
    if(write(f->fd,ptr,size)==-1)
    {
        perror("WriteToFIFO");
        return false;
    }
    return true;
}

void FreeFIFO(FIFO *f)
{
    close(f->fd);
    char temp[10]={0};
    sprintf(temp,"rm -rf %s",f->Name);
    system(temp);
    free(f);

}
